package org.xg.study.servlet;

import com.sun.org.apache.xpath.internal.operations.Bool;

import javax.servlet.*;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @author CMG
 * @version 1.0
 * @description
 * @cLassName BlackListFilter
 * @date 2021/9/24 15:59
 **/
public class BlackListFilter implements Filter {
    private FilterConfig filterConfig;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletResponse.setContentType("text/html;charset=UTF-8");
        Boolean success = true;
        String name = servletRequest.getParameter("username");
        Enumeration<String> blackListNames = filterConfig.getInitParameterNames();
        if (null == name || "".equals(name)) {
            servletResponse.getWriter().write("用户名不能为空！");
        } else {
            while (blackListNames.hasMoreElements()) {
                if (filterConfig.getInitParameter(blackListNames.nextElement()).equals(name)) {
                    success = false;
                }
            }
            if (success) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                servletResponse.getWriter().write("<h1 align=\"center\" style=\"font-family:arial;color:red;" +
                        "\">温馨提示：您存在风险，暂时不能为您提供服务<h1>\n");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
